import axios from "axios";

/**
 * 下载文件
 * @param file 文件
 */
export const downSelectFile = (file:File) => {
    let blob = new Blob([file], {
        type: file.type,
    });
    let downloadElement = document.createElement("a");
    let href = window.URL.createObjectURL(blob); //创建下载链接
    let fileName = "";

    fileName = new Date().getTime().toString();
    downloadElement.href = href;
    downloadElement.download = decodeURIComponent(fileName); //解码
    document.body.appendChild(downloadElement);
    downloadElement.click();
    document.body.removeChild(downloadElement);
    window.URL.revokeObjectURL(href); //释放掉blob对象
}

export const downURLFile =async (url:string) => {
    const res:any = await getFile(url)

    let downloadElement = document.createElement("a");
    let href = window.URL.createObjectURL(res.data); //创建下载链接
    let fileName = "";

    fileName = new Date().getTime().toString();
    downloadElement.href = href;
    downloadElement.download = decodeURIComponent(fileName); //解码
    document.body.appendChild(downloadElement);
    downloadElement.click();
    document.body.removeChild(downloadElement);
    window.URL.revokeObjectURL(href); //释放掉blob对象
}

const getFile = (url: string) => {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            responseType: "blob"
        }).then((res: any) => {
            resolve(res)
        }).catch((error: any) => {
            reject(error)
        })
    })
}
//创建bolb 链接
export const getBolbUrl = (file:File) => {
    return window.URL.createObjectURL(new Blob([file], { type: file.type }))
}